﻿#include "websocket/websocketmanager.h"
#include "websocket/HttpClientConnection.h"
#include "websocket/LiveManager.h"
#include <qdebug.h>

#include <assert.h>
#include "base/TraceLog.h"


WebSocketManager::WebSocketManager()
    :server(NULL)
    ,master_live_manager(NULL)
{


}
WebSocketManager::~WebSocketManager()
{
    if(master_live_manager)
    {
        delete master_live_manager;
    }

    stopWebSocket();
}

int WebSocketManager::InitLiveManager()
{
    master_live_manager = new LiveManager(this);
    assert(master_live_manager != NULL);
    return 0;
}

int WebSocketManager::startWebSocket(int port)
{
    server = new QWebSocketServer("WebliveServer", QWebSocketServer::NonSecureMode, this);
    connect(server, &QWebSocketServer::acceptError, this, &WebSocketManager::onAcceptError);
    connect(server, &QWebSocketServer::serverError, this, &WebSocketManager::onServerError);
    connect(server, &QWebSocketServer::newConnection, this, &WebSocketManager::onNewConnection);
    connect(server, &QWebSocketServer::closed, this, &WebSocketManager::closed);

    server->listen(QHostAddress::AnyIPv4, port);
    QString message = QString("%1 started on port %2").arg(QCoreApplication::applicationName()).arg(server->serverPort());
    qDebug().noquote() << message;

    return 0;
}
int WebSocketManager::stopWebSocket()
{
    QMutexLocker locker(&cs_live_);
    server->close();

    //delete all connections
    qDeleteAll(clients.begin(), clients.end());
    clients.clear();

    return 0;
}

void WebSocketManager::onAcceptError(QAbstractSocket::SocketError socketError)
{
    qDebug() << "Accept error:" << socketError;
}

void WebSocketManager::onServerError(QWebSocketProtocol::CloseCode closeCode)
{
    qDebug() << "Server error:" << closeCode;
}

void WebSocketManager::onNewConnection()
{
    QMutexLocker locker(&cs_live_);
    //将下一个挂起的连接以QTcpSocket对象的形式返回
    QWebSocket* socket = server->nextPendingConnection();

    if (!socket)
    {
        return;
    }

    //查询同一个地址再次连接
    QList<HttpClientConnection*>::iterator it;

//    for(it=clients.begin();it!=clients.end();)
//    {
//        HttpClientConnection* http = *it;
//        if ( http->get_client_address() == socket->peerAddress())
//        {
//            LogDEBUG("new Connection same with: %s",http->get_client_address().toString().toStdString().c_str());
//            LogDEBUG("remove before connection. now delete...");
//            it=clients.erase(it);
//            delete http;
//            http = NULL;
//            break;
//        }
//    }

//    for ( int i=0; i!=clients.size(); ++i )
//    {
//       if ( clients.at(i)->get_client_address() == socket->peerAddress())
//       {
//           LogDEBUG("new Connection same with: %s",clients.at(i)->get_client_address().toString().toStdString().c_str());
//           LogDEBUG("remove before connection. now no delete...");
//           HttpClientConnection* tmp = clients.at(i);
//           clients.removeAll(tmp);
//           delete tmp;
//           tmp = NULL;
//           //break;
//       }

//    }

    LogDEBUG("create new connection....");
    HttpClientConnection* client = new HttpClientConnection(socket,this,master_live_manager);

    client->Init();

    // Remove client on disconnection
    connect(client, &HttpClientConnection::disconnected,this,&WebSocketManager::LivesocketDisconnected);

    clients << client;

    LogDEBUG("Connection with: %s",socket->peerAddress().toString().toStdString().c_str());
}


void WebSocketManager::LivesocketDisconnected()
{
    QMutexLocker locker(&cs_live_);

    HttpClientConnection* client = qobject_cast<HttpClientConnection*>(sender());
    LogDEBUG("LivesocketDisconnected:%s",client->get_client_address().toString().toStdString().c_str());
    clients.removeAll(client);
    delete client;
    client = NULL;
}

int WebSocketManager::SendRemovePull(QString &url)
{
    for ( int i=0; i!=clients.size(); ++i )
    {
        //clients.at(i)->SendToClientRemove(url);
    }


   return 0;
}



